package com.qyx.pmpucat.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.qyx.pmpucat.common.exception.ClientException;
import com.qyx.pmpucat.entity.OptionCategory;
import com.qyx.pmpucat.mapper.OptionCategoryMapper;
import com.qyx.pmpucat.service.OptionCategoryService;
import com.qyx.pmpucat.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 选项分类服务实现
 */
@Service
@RequiredArgsConstructor
public class OptionCategoryServiceImpl implements OptionCategoryService {

    private final OptionCategoryMapper optionCategoryMapper;
    private final UserService userService;

    @Override
    public Long createOptionCategory(OptionCategory optionCategory) {
        // 设置创建人信息
        Long userId = StpUtil.getLoginIdAsLong();
        optionCategory.setCreateBy(userId);
        optionCategory.setCreateUser(userService.getById(userId).getUsername());

        // 保存选项分类
        optionCategoryMapper.insert(optionCategory);

        return optionCategory.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOptionCategory(OptionCategory OptionCategory) {
        // 检查选项分类是否存在
        Long id = OptionCategory.getId();
        if (id == null) {
            throw new ClientException("选项分类ID不能为空");
        }
        // 更新选项分类
        optionCategoryMapper.update(OptionCategory);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOptionCategory(Long id) {
        // 检查选项分类是否存在
        OptionCategory existOptionCategory = optionCategoryMapper.selectOneById(id);
        if (existOptionCategory == null) {
            throw new ClientException("选项分类不存在");
        }

        // TODO: 检查是否有问题正在使用此选项分类
        // 可以添加业务逻辑检查是否有问题关联了此选项分类

        // 删除选项分类
        optionCategoryMapper.deleteById(id);
    }

    @Override
    public OptionCategory getOptionCategoryDetail(Long id) {
        return optionCategoryMapper.selectOneById(id);
    }

    @Override
    public List<OptionCategory> getAllOptionCategories() {
        // 查询所有选项分类，按排序号升序排列
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.orderBy("sort", true);
        queryWrapper.orderBy("id", true);
        List<OptionCategory> optionCategories = optionCategoryMapper.selectListByQuery(queryWrapper);

        return optionCategories;
    }
}